package com.qifenqian.turbot.module.ui.marketing

import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Canvas
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.text.InputType
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback
import com.chad.library.adapter.base.listener.OnItemSwipeListener
import com.qifenqian.turbot.base.BaseActivity
import com.qifenqian.turbot.config.Constant
import com.qifenqian.turbot.config.TurbotEnum
import com.qifenqian.turbot.module.adapter.marketing.FullReductionAdapter
import com.qifenqian.turbot.module.contract.MarketingContract
import com.qifenqian.turbot.module.entity.response.marketing.FullReductionEntity
import com.qifenqian.turbot.module.presenter.MarketingPresenter
import com.qifenqian.turbot.util.Lcat
import com.qifenqian.turbot.util.SpUtils
import com.qifenqian.turbot.widget.CommonDialog
import com.riqthen.superedittext.SuperEditText
import kotlinx.android.synthetic.main.activity_full_reduction.*
import org.jetbrains.anko.toast
import java.text.SimpleDateFormat

/**
 * @author H
 * @createDate 9/1/4 11:45
 * @description 满减活动
 * @see
 * @since
 */
class FullReductionActivity : BaseActivity<MarketingPresenter, MarketingContract.View>(), MarketingContract.View {

    companion object {
        fun startThis(context: Context) {
            val intent = Intent(context, FullReductionActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun bindLayoutId(): Int = com.qifenqian.turbot.R.layout.activity_full_reduction

    override fun bindPresenter(): MarketingPresenter? = MarketingPresenter(this, this)

    private var mDiscountType = 0   //替换成FullReductionEntity中的某个参数(isShare)
    private var mMoneyOffAmountList: MutableList<FullReductionEntity.MoneyOffAmount> = mutableListOf()
    private var mFullReductionAdapter: FullReductionAdapter? = null
    override fun initial() {
        mPresenter?.getFullReduction()
        val moneyOffAmountRequestList = mutableListOf<FullReductionEntity.MoneyOffAmount>()
        val fullReductionRequest = FullReductionEntity(moneyOffAmountList = moneyOffAmountRequestList)
        swi_full_reduction_open.setOnCheckedChangeListener { buttonView, isChecked ->
            ly_full_reduction_detail.visibility = if (isChecked) View.VISIBLE else View.GONE
            fullReductionRequest.isOpen = if (isChecked) 1 else 0
        }
        swi_full_reduction_discount.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                ly_full_reduction_discount.visibility = View.VISIBLE
                v_full_reduction_discount1.isSelected = true
                v_full_reduction_discount2.isSelected = false
                v_full_reduction_discount3.isSelected = false
                mDiscountType = 1
            } else {
                ly_full_reduction_discount.visibility = View.GONE
                mDiscountType = 0
            }
            fullReductionRequest.isShare = if (isChecked) 1 else 0
        }
        swi_full_reduction_show_homepage.setOnCheckedChangeListener { buttonView, isChecked ->
            fullReductionRequest.priority = if (isChecked) TurbotEnum.PRIORITY_FULL_REDUCTION.type else mFullReductionEntity?.priority!!
        }
        ly_full_reduction_discount1.setOnClickListener {
            mDiscountType = 1
            v_full_reduction_discount1.isSelected = true
            v_full_reduction_discount2.isSelected = false
            v_full_reduction_discount3.isSelected = false
        }
        ly_full_reduction_discount2.setOnClickListener {
            mDiscountType = 2
            v_full_reduction_discount1.isSelected = false
            v_full_reduction_discount2.isSelected = true
            v_full_reduction_discount3.isSelected = false
        }
        ly_full_reduction_discount3.setOnClickListener {
            mDiscountType = 3
            v_full_reduction_discount1.isSelected = false
            v_full_reduction_discount2.isSelected = false
            v_full_reduction_discount3.isSelected = true
        }
        rv_full_reduction_content.layoutManager = LinearLayoutManager(this)
        mFullReductionAdapter = FullReductionAdapter(mMoneyOffAmountList)
        rv_full_reduction_content.adapter = mFullReductionAdapter
        ItemTouchHelper(ItemDragAndSwipeCallback(mFullReductionAdapter)).attachToRecyclerView(rv_full_reduction_content)
        mFullReductionAdapter!!.enableSwipeItem()
        mFullReductionAdapter!!.setOnItemSwipeListener(object : OnItemSwipeListener {
            override fun clearView(viewHolder: RecyclerView.ViewHolder?, pos: Int) {}
            override fun onItemSwiped(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
                if (mMoneyOffAmountList.isNullOrEmpty()) {
                    mFullReductionAdapter?.setEmptyView(com.qifenqian.turbot.R.layout.layout_empty, rv_full_reduction_content)
                }
            }

            override fun onItemSwipeStart(viewHolder: RecyclerView.ViewHolder?, pos: Int) {}
            override fun onItemSwipeMoving(canvas: Canvas?, viewHolder: RecyclerView.ViewHolder?, dX: Float, dY: Float, isCurrentlyActive: Boolean) {}
        })
        btn_full_reduction_add.setOnClickListener {
            showEditDialog()
        }
        tv_full_reduction_limit_time.setOnClickListener {
            showDatePickDialog(true)
        }
        btn_full_reduction_save.setOnClickListener {
            Lcat.a("FullReductionActivity", InputType.TYPE_CLASS_DATETIME)
            fullReductionRequest.moneyOffAmountList = mMoneyOffAmountList
            fullReductionRequest.restaurantId = SpUtils.getInstance().getInt(Constant.SP_KEY_RESTAURANT_ID, -1, Constant.SP_ACCOUNT)
            fullReductionRequest.startTime = mStartTime
            fullReductionRequest.endTime = mEndTime
            Lcat.a("mMoneyOffAmountList", mMoneyOffAmountList)
            Lcat.a("fullReductionRequest", fullReductionRequest)
            mPresenter?.saveFullReduction(fullReductionRequest)
        }
    }

    private fun showEditDialog() {
        val editDialog = CommonDialog(this)
        val etConsume = SuperEditText(this)
        val etDiscountMoney = SuperEditText(this)
        etConsume.hint = "设置消费金额"
        etConsume.textSize = 16f
        etConsume.setBackgroundResource(com.qifenqian.turbot.R.drawable.bg_bottom_line)
        etConsume.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
        etDiscountMoney.hint = "设置满减金额"
        etDiscountMoney.textSize = 16f
        etDiscountMoney.setBackgroundResource(com.qifenqian.turbot.R.drawable.bg_bottom_line)
        etDiscountMoney.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
        editDialog.setTitleText("添加满减信息")
                .setViews(etConsume, etDiscountMoney)
                .setCancel("取消", DialogInterface.OnClickListener { dialog, which ->
                    dialog!!.dismiss()
                })
                .setOk("确定", DialogInterface.OnClickListener { dialog, which ->
                    if (etConsume.text.toString().isBlank()) {
                        toast("请输入消费金额")
                        return@OnClickListener
                    }
                    if (etDiscountMoney.text.toString().isBlank()) {
                        toast("请输入满减金额")
                        return@OnClickListener
                    }
                    mMoneyOffAmountList.add(FullReductionEntity.MoneyOffAmount(0, 0,
                            etConsume.removeHanziAndLetters().toDouble() * 100, etDiscountMoney.removeHanziAndLetters().toDouble() * 100))
                    mFullReductionAdapter?.notifyItemInserted(mMoneyOffAmountList.size)
                    dialog!!.dismiss()
                })
                .setCommonCancelable(true)
                .setCommonCanceledOnTouchOutside(true)
                .show()
    }

    private var mFullReductionEntity: FullReductionEntity? = null
    private var mStartTime: String = ""
    private var mEndTime: String = ""
    private fun showDatePickDialog(start: Boolean) {
        val pvTime = TimePickerBuilder(this, OnTimeSelectListener { date, v ->
            if (start) {
                mStartTime = SimpleDateFormat("yyyy-MM-dd HH:mm").format(date)
                showDatePickDialog(false)
            } else {
                mEndTime = SimpleDateFormat("yyyy-MM-dd HH:mm").format(date)
                tv_full_reduction_limit_time.text = "$mStartTime 至 $mEndTime"
            }
        }).setTimeSelectChangeListener { Log.i("pvTime", "onTimeSelectChanged") }
                .setType(booleanArrayOf(true, true, true, true, true, false))
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .build()
        val dialog = pvTime.dialog
        if (dialog != null) {
            val params = FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM
                                                 )
            params.leftMargin = 0
            params.rightMargin = 0
            pvTime.dialogContainerLayout.layoutParams = params
            val dialogWindow = dialog.window
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim)//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM)//改成Bottom,底部显示
            }
        }
        dialog.show()
    }

    override fun getFullReductionResult(isSuccess: Boolean, code: Int, msg: String?, t: FullReductionEntity?) {
        if (isSuccess) {
            mFullReductionEntity = t
            if (mFullReductionEntity?.isOpen == 1) {
                swi_full_reduction_open.isChecked = true
                ly_full_reduction_detail.visibility = View.VISIBLE
            } else {
                swi_full_reduction_open.isChecked = false
                ly_full_reduction_detail.visibility = View.GONE
            }
            swi_full_reduction_open.isChecked = t?.isOpen == 1
            ly_full_reduction_detail.visibility = if (t?.isOpen == 1) View.VISIBLE else View.GONE
            swi_full_reduction_discount.isChecked = t?.isShare == 1
//            ly_full_reduction_discount.visibility = if (mFullReductionEntity?.isShare == 1) View.VISIBLE else View.GONE
            mMoneyOffAmountList.clear()
            mMoneyOffAmountList.addAll(t!!.moneyOffAmountList)
            if (mMoneyOffAmountList.isNullOrEmpty()) {
                mFullReductionAdapter?.setEmptyView(com.qifenqian.turbot.R.layout.layout_empty, rv_full_reduction_content)
            }
            mFullReductionAdapter?.notifyDataSetChanged()
            tv_full_reduction_limit_time.text = "${t?.startTime} - ${t?.endTime}"
            when (mDiscountType) {
                0 -> {
                    swi_full_reduction_discount.isChecked = false
                }
                1 -> {
                    swi_full_reduction_discount.isChecked = true
                    v_full_reduction_discount1.isSelected = true
                    v_full_reduction_discount2.isSelected = false
                    v_full_reduction_discount3.isSelected = false
                }
                2 -> {
                    swi_full_reduction_discount.isChecked = true
                    v_full_reduction_discount1.isSelected = false
                    v_full_reduction_discount2.isSelected = true
                    v_full_reduction_discount3.isSelected = false
                }
                3 -> {
                    swi_full_reduction_discount.isChecked = true
                    v_full_reduction_discount1.isSelected = false
                    v_full_reduction_discount2.isSelected = false
                    v_full_reduction_discount3.isSelected = true
                }
            }
            swi_full_reduction_show_homepage.isChecked = t.priority == TurbotEnum.PRIORITY_FULL_REDUCTION.type
        } else {
            toast(msg!!)
            showErrorPage(View.OnClickListener { mPresenter?.getFullReduction() }, msg)
        }
    }

    override fun saveFullReductionResult(isSuccess: Boolean, code: Int, msg: String?) {
        if (isSuccess) {
            finishDelay()
        }
        toast(msg!!)
    }
}
